package com.study.rabbitmq.basic.defaultexchange;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class DefaultExchangeProducerTest {
	public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("192.168.20.68");
		factory.setPort(5672);
		factory.setUsername("leke");
		factory.setPassword("leke@@@");

		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel(5);

		String queueName = "DefaultExchangeProducerTest";

		channel.queueDeclare(queueName,false,false,false,null);

//		for(int i=0; i<100; i++){
//			channel.basicPublish("", queueName, null, ("DefaultExchangeProducerTest"+i).getBytes());
//			Thread.sleep(1000);
//		}

		//异常处理
		//找不到对应的exchange 或 queue  发送消息时mandatory为true 返回客户端消息
		ReturnListener returnListener = new ReturnListener() {
			@Override
			public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
				System.out.println("return "+new String(body));
			}
		};
		channel.addReturnListener(returnListener);
		boolean mandatory = true;
		String fanoutExchangeName = "fanoutmandatoryExchange";
		String directExchangeName = "directmandatoryExchange";
		String topicExchangeName = "topicmandatoryExchange";
		channel.exchangeDeclare(topicExchangeName,"topic",false,false,null);
		channel.basicPublish(fanoutExchangeName,"ffffffghfghgh",mandatory,null,"cannotfindqueue".getBytes());
		channel.basicPublish("gfdgdfg",queueName,mandatory,null,"cannotfindexchange".getBytes());

	}
}
